package com.liu.upload;

import com.liu.utils.StreamUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author liuchengjie
 */
public class SocketFileUploadServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("服务端监听8888");
        Socket socket = serverSocket.accept();
        String pathTarget = "file.png";
        //得到输入流
        BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());
        //得到文件字节数组
        byte[] bytes = StreamUtils.streamToByteArray(bufferedInputStream);

        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(pathTarget));
        bufferedOutputStream.write(bytes);
        bufferedOutputStream.flush();
        //向客户端回复收到图片
        BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
        out.write("兄弟，图片收到了".getBytes());
        out.flush();
        out.close();

        bufferedOutputStream.close();
        bufferedInputStream.close();
        socket.close();
        serverSocket.close();
    }

}
